﻿using System.Diagnostics;
using System.Linq;

namespace WindowsFormsApplication1
{
    public class Comparer
    {
        private readonly CompareOperationState _state;
        public int FilesCompared { get; private set; }

        public Comparer(CompareOperationState state)
        {
            _state = state;
        }

        public void Process()
        {
            _state.CompareState = CompareOperationState.State.Started;
            FilesCompared = 1;
            Debug.WriteLine("Comparer::Process started");
            int curr = 1;
            while (_state.EnumerationState != CompareOperationState.State.Canceled 
                && !(_state.EnumerationState == CompareOperationState.State.Completed && FilesCompared == _state.ItemList.Count))
            {
                if (curr >= _state.ItemList.Count) continue;
                var i1 = _state.ItemList[curr];
                for (var i = 0; i < curr; i++)
                {
                    var i2 = _state.ItemList[i];
                    var areEqual = CompareFiles(i1, i2);
                    if (areEqual)
                    {
                        i1.Duplicates.Add(i);
                        i2.Duplicates.Add(curr);
                    }
                }

                curr++;
                FilesCompared++;
            }
        
            _state.CompareState = CompareOperationState.State.Completed;
            Debug.WriteLine("Comparer::Process count: " + FilesCompared);
        }

        public bool CompareFiles(ItemInfo i1, ItemInfo i2)
        {
            if (i1.Size != i2.Size) return false;
            if (i1.Hash.Length != i2.Hash.Length) return false;
            return !i1.Hash.Where((t, i) => t != i2.Hash[i]).Any();
        }
    }
}